const app = getApp()
const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    del: [],
    photo:[],
    imgUrl:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    wx.getLocation({
      type: 'wgs84',
      altitude: true,
      fail: (res) => {
        //不允许打开定位
        wx.hideLoading()
        wx.getSetting({
          success(res) {
            //开启小程序内定位
            if (res.authSetting["scope.userLocation"] == false) {
              wx.showModal({
                content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
                confirmText: "去设置",
                success: res => {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/mine/mine'
                    })
                  }
                }
              })
            } else {
              //开启系统设置定位
              wx.getSystemInfo({
                success: res => {
                  console.log(res)
                  if (res.platform == "ios") {
                    that.setData({
                      locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                    })
                  }
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                },
                fail: res => {
                  wx.showModal({
                    title: '未允许使用地理位置',
                    content: that.data.locationContent,
                    showCancel: false
                  })
                }
              })
            }

          }
        })
      },
      success: res => {
        console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          altitude: res.altitude
        })
      }
    })
    let photo = [],
      imageStr = null,
      imageNum = 0,
      contentLength
    wx.getStorage({
      key: 'updateInspect' + options.id,
      success: function(res) {
        console.log("res",res.data)
        if (res.data.photo[0] != "") {
          imageNum = res.data.photo.length
          for (let i = 0; i < res.data.photo.length; i++) {
            photo[i] = res.data.photo[i]
          }
          if (imageNum == 3) {
            that.setData({
              hide: true
            })
          }
        }
        if (res.data.recordContent == null) {
          contentLength = 0
        } else {
          contentLength = res.data.recordContent.length
        }
        that.setData({
          id: res.data.id,
          categoryId: res.data.categoryId,
          inspectItemId: res.data.inspectItemId,
          item: res.data.item,
          status: res.data.status,
          content: res.data.content,
          photo: photo,
          video: res.data.video,
          videoSrc: res.data.videoSrc,
          imageNum: imageNum,
          recordContent: res.data.recordContent,
          contentLength: contentLength,
          className: res.data.className,
          address: res.data.address
        })
        wx.hideLoading()
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
      }
    })
  },

  switchChange: function(e) {
    if (e.detail.value == false) {
      this.setData({
        status: 4,
        contentLength: 0,
        photo: [],
        hide: false,
        imageNum: 0,
        video: "",
        videoSrc:""
      })
    } else {
      this.setData({
        status: 3,
        recordContent: null,
        contentLength: 0,
        photo: [],
        imageNum: 0,
        video: "",
        videoSrc:""
      })
    }
  },


  inputContent: function(e) {
    e.detail.value = app.trim(e.detail.value)
    this.setData({
      contentLength: parseInt(e.detail.value.length),
      recordContent: e.detail.value
    })
  },
  onShow:function(e){
    var that = this;
    let photo = that.data.photo
    let imgUrl = that.data.imgUrl
    if(photo != undefined){
      var imageNum = photo.length
      if(photo.length == 3){
        that.setData({
          photo: photo,
          imgUrl: imgUrl,
          imageNum :imageNum,
          hide:true
        })
      }else{
        that.setData({
          photo: photo,
          imgUrl: imgUrl,
          imageNum :imageNum,
          hide:false
        })
      }
    }
  },
  
  //自定义相机组件
  toCamera:function(e){
    wx.navigateTo({
      url: '../../subpages/pages/cameraIdentified/cameraIdentified?recordContent='+this.data.recordContent+
      '&type=3'+'&address='+this.data.address+'&photo='+JSON.stringify(this.data.photo)+'&item='+this.data.item+
      '&content='+this.data.content
    })
  },

  chooseImage: function(e) {
    var that = this;
    let photo = this.data.photo
    let imageNum = this.data.imageNum
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        wx.showLoading({
          title: "图片上传中",
          mask: true
        })

        let tempImg = res.tempFilePaths
        let imgUrl = []
        for (let i = 0; i < tempImg.length; i++) {
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload',
            filePath: res.tempFilePaths[i],
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {

              if (res.data == "fail") {
                wx.showToast({
                  title: "图片上传失败",
                  image: "/images/error.png"
                })
              } else {
                wx.showToast({
                  title: "上传成功"
                })
                photo.push(app.imageUrl + res.data)
                imgUrl.push(res.data)
                imageNum++
                this.setData({
                  photo: photo,
                  imageNum: this.data.photo.length,
                })
                if (this.data.imageNum == 3) {
                  this.setData({
                    hide: true
                  })
                }
              }
            },
            fail: res => {
              wx.showToast({
                title: "图片上传失败",
                image: "/images/error.png"
              })
            }
          })
        }
      }
    })
  },


  previewImageDeal: function(e) {
    let current = e.currentTarget.id
    wx.previewImage({
      current: current,
      urls: this.data.photo
    })
  },


  deleteImage: function(e) {
    let that = this,
      imgIndex = parseInt(e.currentTarget.id),
      photo = this.data.photo,
      target = photo[imgIndex],
      temp = [],
      del = this.data.del
    for (let i = 0; i < photo.length; i++) {
      if (i != imgIndex) {
        temp.push(photo[i])
      } else {
        del.push(photo[i])
      }
    }
    wx.showActionSheet({
      itemList: ['删除这张照片'],
      success: res => {
        if (!res.cancel) {
          that.setData({
            photo: temp,
            del: del,
            imageNum: that.data.imageNum - 1,
            hide: false
          })
          // wx.request({
          //   url: app.inspectUrl + '/weChatSystem/deleteFile',
          //   method: 'POST',
          //   data: {
          //     filename: target.split("image/")[1]
          //   },
          //   dataType: 'json',
          //   success: res => {
          //     let imageNum = that.data.imageNum - 1
          //     that.setData({
          //       imageNum: imageNum,
          //     })
          //     if (that.data.imageNum != 3) {
          //       that.setData({
          //         hide: false
          //       })
          //     }
          //   }
          // })
        }
      }
    })
    // that.setData({
    //   imageStr: temp.join(",")
    // })
    // console.log("that.data.imageStr2",that.data.imageStr)
  },


  submit: util.throttle(function(e) {
    let that = this,
      item = this.data,
      commit

    if (item.status == 4) {
      if (item.recordContent == null || item.recordContent == undefined || item.recordContent == "") {
        commit = 0
      }
    }
    if (commit == 0) {
      wx.showToast({
        title: '请输入现场问题描述',
        image: "/images/warning.png"
      })
    } else {
      wx.showModal({
        title: "",
        content: "是否保存当前修改",
        success(res) {
          if (res.confirm) {
            that.commitForm()
          }
        }
      })
    }
  }),


  commitForm: function() {
    let that = this
    let dataPhoto = this.data.photo
    let photo = ""
    for (let i = 0; i < this.data.photo.length; i++) {
      if (i == dataPhoto.length - 1) {
        photo = photo + dataPhoto[i].substring(dataPhoto[i].indexOf("/image/"))
      } else {
        photo = photo + dataPhoto[i].substring(dataPhoto[i].indexOf("/image/")) + ","
      }
    }

    wx.request({
      url: app.inspectUrl + '/WeChat/weChatSystem/updateInspectConditionById',
      method: 'POST',
      data: {
        id: this.data.id,
        photo: photo,
        video: this.data.video,
        recordContent: this.data.recordContent,
        status: this.data.status,
        updateUserId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        for (let i = 0; i < that.data.del.length; i++) {
          let del = that.data.del[i].split("image/")[1]
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteFile',
            method: 'POST',
            data: {
              filename: del
            },
            dataType: 'json',
            success: res => {

            }
          })
        }


        wx.showToast({
          title: '提交成功',
          mask: true
        })
        //异常推送
        if (4 == that.data.status) {
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/safetyReport',
            method: 'POST',
            data: {
              schoolId: app.globalData.departmentId,
              safetyLevel: 5,
              categoryId: that.data.categoryId,
              address: that.data.address,
              content: that.data.recordContent,
              photo: photo,
              // photo: that.data.imageStr,
              video:that.data.video,
              reporter: app.globalData.userId,
              inspectConditionId: that.data.id,
              itemContent: that.data.content,
              latitude: this.data.latitude,
              longitude: this.data.longitude,
              altitude: this.data.altitude
            },
            dataType: 'json',
            success: res => {
              if (res.data.res == "success") {
                let safetySceneId = res.data.data
                wx.request({
                  url: app.inspectUrl + '/WeChat/weChatSystem/getAccessTokenForSendMsg',
                  method: 'GET',
                  dataType: 'json',
                  success: res => {
                    let access_token = res.data.access_token
                    wx.request({
                      url: app.inspectUrl + '/WeChat/weChatSystem/getChargeManWeChatId',
                      method: 'POST',
                      data: {
                        categoryId: that.data.categoryId,
                        schoolId: app.globalData.departmentId
                      },
                      dataType: 'json',
                      success: res => {
                        let unbind = []
                        for (let i = 0; i < res.data.length; i++) {
                          if (res.data[i].res == "success") {
                            let datetime = util.formatTime(new Date())
                            wx.request({
                              url: app.inspectUrl + '/WeChat/weChatSystem/sendMessage',
                              data: {
                                template: 1,
                                accessToken: access_token,
                                touser: res.data[i].msg,
                                safetySceneId: safetySceneId,
                                data: {
                                  first: {
                                    value: "【巡检异常】"
                                  },
                                  keyword1: {
                                    value: app.globalData.realname
                                  },
                                  keyword2: {
                                    value: datetime
                                  },
                                  keyword3: {
                                    value: `巡检时在${this.data.address}发现异常，请及时查看!`
                                  }
                                }
                              },
                              method: 'POST',
                              dataType: 'json'
                            })
                          } else {
                            unbind.push(res.data[i].msg)
                          }
                        }
                        if (unbind.length != 0) {
                          let msg = unbind.join("、") + "主管未绑定服务号，无法正常接收推送！"
                          wx.showModal({
                            title: "提示",
                            showCancel: false,
                            content: msg,
                          })
                        }
                      }
                    })
                  },
                  complete: () => {
                    wx.removeStorage({
                      key: 'updateInspect' + this.data.id
                    })
                    wx.removeStorageSync('inspectitemOriginal')
                    setTimeout(function() {
                      let pages = getCurrentPages();
                      let prevPage = pages[pages.length - 2];
                      prevPage.setData({
                        submitRefresh: 1
                      });
                      // 提示框隐藏后 跳转
                      wx.navigateBack({
                        delta: 1
                      })
                    }, 1000)
                  }
                })
              } else {
                wx.showToast({
                  title: '上报失败',
                  image: "/images/error.png"
                })
              }
            },
            fail: res => {
              wx.showToast({
                title: '网络异常！',
                image: '/images/warning.png'
              })
            }
          })
        }
      },
      fail: res => {
        wx.showToast({
          title: '网络异常！',
          image: '/images/warning.png'
        })
      }
    })
  },

  //新增视频录制功能
  press:function (e) {
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      camera: 'back',
      success: res => {
        if(res.size > 2097152){
          wx.showToast({
            title: '文件大于2M！',
            mask: true,
            image: "/images/error.png"
          })
        }else{
          wx.uploadFile({
            url: app.inspectUrl + '/WeChat/weChatSystem/fileUpload2',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success:res=>{
              console.log(res.data)
              this.setData({
                videoSrc: app.imageUrl+res.data,
                video: res.data
              })
            }
          })
        }
      },
      fail(res){
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo:function(e) {
    let target = this.data.video
    wx.showActionSheet({
      itemList: ['删除视频'],
      success: res => {
        if (!res.cancel) {
          wx.request({
            url: app.inspectUrl + '/WeChat/weChatSystem/deleteVideo',
            method: 'POST',
            data: {
              filename: target.split("video/")[1]
            },
            dataType: 'json',
            success: res => {
              if(res.data == "success"){
                this.setData({
                  video : ""
                })
              }
            }
          })
        }
      }
    })
  }

})